package com.xy.iot.netty.util;

import com.xy.iot.common.enums.MessageFormatDataEnum;
import com.xy.iot.common.message.BaseMessage;
import com.xy.iot.netty.handle.DelimiterMessageDecoder;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class SendUtil {
    /**
     * 发送数据信息
     * @param channel 信道
     * @param baseMessage 消息数据信息
     */
    public static void sendData(final Channel channel, BaseMessage baseMessage){
        sendData(channel,getByteBuf(baseMessage));
    }
    /**
     * 发送数据信息
     * @param channel 信道
     * @param message 消息数据信息
     */
    public static void sendData(final Channel channel,ByteBuf message){
        if (channel.isActive()) { // 确保通道是激活的
            channel.writeAndFlush(message).addListener(future -> {
                if (future.isSuccess()) {
                    log.info("发送消息成功");
                } else {
                    log.error("发送消息失败", future.cause());
                }
            });
        }else {
            log.error("通道不可用");
        }

    }

    /**
     * 得到发送数据信息
     * @param baseMessage
     * @return
     */
    public static ByteBuf getByteBuf(BaseMessage baseMessage){
        MessageFormatDataEnum messageDataEnum = MessageFormatDataEnum.getMessageFormatDataEnum(baseMessage.getDataType());
        log.info("messageDataEnum：{},发送数据：{}", messageDataEnum, baseMessage);
        baseMessage.buildResponseData();
        return getByteBuf(baseMessage.toBytes());
    }

    /**
     * 得到发送数据信息
     * @param data
     * @return
     */
    public static ByteBuf getByteBuf(byte[] data){
        ByteBuf msg = Unpooled
                .buffer();
        msg.writeBytes(data);
        msg.writeBytes(DelimiterMessageDecoder.DELIMITER_DATA);
        return msg;
    }
}
